<template>
    <div>
        <el-row>
          <el-col :span="8">
            <el-button type="primary" :icon="CirclePlusFilled" @click="addData.dialog = true">新增角色</el-button>
            <el-dialog :append-to-body="true" draggable v-model="addData.dialog" title="角色编辑" width="35%">
                <el-form :model="addData" label-width="70px">
                  <el-form-item  label="角色名称">
                    <el-input v-model="addData.name" />
                  </el-form-item>
                  <el-form-item label="角色标识">
                    <el-input v-model="addData.permission"/>
                  </el-form-item>
                  <el-form-item label="角色描述">
                    <el-input type="textarea" v-model="addData.description"/>
                  </el-form-item>
                </el-form>
                <template #footer>
                  <span class="dialog-footer">
                    <el-button @click="addData.dialog = false">关闭</el-button>
                    <el-button type="primary" @click="addRole()">
                      添加
                    </el-button>
                  </span>
                </template>
              </el-dialog>
          </el-col>
        </el-row>
        <el-table border stripe :data="roleData"
        style="width: 100%;margin-top: 10px;" 
        :header-cell-style="{'background':'#C0C4CC','color':'white'}">
            <el-table-column label="序号" width="80">
                <template #default="scope"> 
                    <el-tag type="info">{{scope.row.id}}</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="名称" width="120">
                <template #default="scope"> 
                    <el-tag :type="scope.row.tag">{{scope.row.name}}</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="标识" width="150">
                <template #default="scope"> 
                    <el-tag effect="dark" :type="scope.row.tag">{{scope.row.permission}}</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="description" label="描述" width="550"/>
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button type="primary" :icon="Menu" @click="getMenu(scope.row.id)">分配菜单</el-button>
                    <el-dialog :append-to-body="true" draggable v-model="scope.row.menuDialog" title="分配菜单" @close="DialogClose" width="18%">
                        <el-card shadow="always">
                            <el-tree
                                :data="menuAll"
                                show-checkbox
                                node-key="id"
                                @check="checkNode"
                                :props="menuProps"
                                :default-checked-keys="menuChecked"
                                :default-expand-all="true">
                                <template #default="scope">
                                    <el-icon>
                                        <component :is="scope.data.icon"></component>
                                    </el-icon>
                                    <span>{{scope.data.label}}</span>
                                </template>
                            </el-tree>
                        </el-card>
                        <template #footer>
                          <span class="dialog-footer">
                            <el-button @click="scope.row.menuDialog = false">关闭</el-button>
                            <el-button type="primary" @click="updateMenuTree(scope.row)">
                              修改
                            </el-button>
                          </span>
                        </template>
                      </el-dialog>
                    <el-button type="warning" :icon="Edit" @click="handleEdit(scope.row)">编辑</el-button>
                    <el-dialog :append-to-body="true" draggable v-model="scope.row.dialog" title="角色编辑" width="35%">
                        <el-form :model="editData" label-width="70px">
                          <el-form-item  label="角色名称">
                            <el-input v-model="editData.name" />
                          </el-form-item>
                          <el-form-item label="角色标识">
                            <el-input v-model="editData.permission"/>
                          </el-form-item>
                          <el-form-item label="角色描述">
                            <el-input type="textarea" v-model="editData.description"/>
                          </el-form-item>
                        </el-form>
                        <template #footer>
                          <span class="dialog-footer">
                            <el-button @click="scope.row.dialog = false">关闭</el-button>
                            <el-button type="primary" @click="updateRole(scope.row)">
                              修改
                            </el-button>
                          </span>
                        </template>
                      </el-dialog>
                    <el-popconfirm
                      width="220"
                      confirm-button-text="确认"
                      cancel-button-text="我再想想"
                      cancel-button-type="info"
                      :icon="InfoFilled"
                      icon-color="red"
                      title="你确定删除该角色吗?"
                      @confirm="handleDelete(scope.row)"
                    >
                      <template #reference>
                        <el-button type="danger" :icon="Delete">删除</el-button>
                      </template>
                  </el-popconfirm>
                </template>
              </el-table-column>
        </el-table>
        <el-row style="margin-top: 20px;">
            <el-col :span="8">
                <el-tag type="success" style="height: 32px; vertical-align: middle;font-size: 17px;">
                  共<span style="color: #79bbff;margin-right: 5px;">{{roleData.length}}</span>种角色
                </el-tag>
              </el-col>
            <el-col :span="12" :offset="4">
              <div class="demo-pagination-block" style="float: right;">
                <el-pagination
                  v-model:current-page="currentPage"
                  :page-size="8"
                  :total="3"
                  :background="true"
                  layout="prev, pager, next"
                />
              </div>
            </el-col>
        </el-row>
    </div>
</template>
<script>
    import {ref,reactive} from 'vue'
    import request from '@/utils/request'
    import {useStore} from 'vuex'
    import { ElMessage} from 'element-plus'
    import {Edit,Delete,Menu,CirclePlusFilled,InfoFilled} from '@element-plus/icons-vue'
    export default{
        name:'SystemRole',
        setup() {
            const icon = {Edit,Delete,Menu,CirclePlusFilled,InfoFilled}
            let roleData = ref([])
            let editData = ref([])//编辑数据
            let addData = reactive({
                name:'',permission:'',
                description:'',dialog:false
            }) //添加数据
            let currentPage = ref(1)
            const store = useStore();
            let menuAll = store.state.menu.menuList
            let menuChecked = ref([])
            let treeStatus = ref([])//菜单树的选中的节点
            let halfChecked = ref([])//菜单树拥有子节点，并且子节点只有部分选中的节点
            const menuProps = {
                children: 'children',
                label: 'name',
            }
            const handleEdit = (row) => {
                for(const role of roleData.value) {
                    if(role.id === row.id){
                        editData.value = row
                        role.dialog = true
                    }
                }
            }
            const DialogClose = () => {
                menuChecked.value = []
            }
            const checkNode = (data,tree) => {
                treeStatus.value = tree.checkedKeys
                halfChecked.value = tree.halfCheckedKeys
            }
            //分配菜单
            const updateMenuTree = (row) => {
                console.log(treeStatus.value)
                request({
                    url:'/roleMenu/update/',
                    method:'post',
                    data:{
                        role:store.state.user.role,
                        roleId:row.id,
                        tree:JSON.stringify(treeStatus.value),
                        half:JSON.stringify(halfChecked.value)
                    },
                    headers:{
                        Authorization:"Bearer "+store.state.user.token,
                    }
                }).then((resp) => {
                    if(resp.message === 'success'){
                        row.menuDialog = false
                        ElMessage({message: '修改成功!',type: 'success'})
                    }else{
                        row.menuDialog = false
                        ElMessage({message: '没有权限!',type: 'error'})
                    }
                })
            }
            const getMenu = (roleId) => {
                request({
                    url:'/role/menu/',
                    method:'post',
                    data:{
                        role:store.state.user.role,
                        roleId:roleId
                    },
                    headers:{
                        Authorization:"Bearer "+store.state.user.token,
                    }
                }).then((resp) => {
                    for (const item of resp) {
                        if(item.children.length === 0)
                            menuChecked.value.push(item.id)
                        else if(item.children.length > 0){
                            for (const value of item.children) {
                                menuChecked.value.push(value.id)
                            }
                        }
                    }
                    for (const item of roleData.value) {
                        if(item.id === roleId){
                            item.menuDialog = true;
                        }
                    }
                })
            }
            const handleDelete = (row) => {
                request({
                    url:'/role/delete/',
                    method:'post',
                    data:{
                        id:row.id,
                        role:store.state.user.role
                    },
                    headers:{
                        Authorization:"Bearer "+store.state.user.token,
                    }
                }).then((resp) => {
                    if(resp.message === 'success'){
                        ElMessage({message: '删除成功!',type: 'success'})
                    }else{
                        ElMessage({message: '删除失败!',type: 'error'})
                    }
                    getRoleAll()
                })
            }
            let getRoleAll = () => {
                request({
                    url:'/role/getAll/',
                    method:'get',
                    params:{
                        role:store.state.user.role
                    },
                    headers:{
                        Authorization:"Bearer "+store.state.user.token,
                    }
                }).then((resp) => {
                    for (const item of resp) {
                        item.menuDialog = false
                        item.dialog = false
                        if(item.name === '管理员')
                            item.tag = 'success'
                        else if(item.name === '普通用户')
                            item.tag = 'warning'
                        else if(item.name === '负责人')
                            item.tag = ''
                        else
                            item.tag = 'info'
                    }
                    roleData.value = resp;
                })
            }
            let updateRole = (row) => {
                request({
                    url:'/role/update/',
                    method:'post',
                    data:{
                        ...editData.value,
                        role:store.state.user.role
                    },
                    headers:{
                        Authorization:"Bearer "+store.state.user.token,
                    }
                }).then((resp) => {
                    if(resp.message === 'success'){
                        row.dialog = false
                        ElMessage({message: '修改成功!',type: 'success'})
                    }else{
                        row.dialog = false
                        ElMessage({message: '修改失败!',type: 'error'})
                    }
                    getRoleAll()
                })
            }
            let addRole = () => {
                request({
                    url:'/role/add/',
                    method:'post',
                    data:{
                        role:store.state.user.role,
                        ...addData
                    },
                    headers:{
                        Authorization:"Bearer "+store.state.user.token,
                    }
                }).then((resp) => {
                    if(resp.message === 'success'){
                        addData.dialog = false
                        ElMessage({message: '添加成功!',type: 'success'})
                    }else{
                        addData.dialog = false
                        ElMessage({message: '没有权限!',type: 'error'})
                    }
                    getRoleAll()
                }).catch(() => {})
            }
            getRoleAll()
            return {
                ...icon,
                roleData,
                editData,
                addData,
                currentPage,
                treeStatus,
                handleEdit,
                handleDelete,
                updateRole,
                addRole,
                getMenu,
                menuAll,
                menuChecked,
                menuProps,
                DialogClose,
                checkNode,
                updateMenuTree,
            }
        },
    }
</script>
<style scoped> 

</style>